﻿using Microsoft.AspNetCore.Mvc;
using OrderService.Models;
using System.Diagnostics;

namespace OrderService.Controllers
{
    [ApiController]
    [Route("/api/ordering/orders")]
    public class OrderController : Controller
    {
        private readonly ILogger<OrderController> _logger;

        private static List<Order> Orders = new List<Order>()
        {
            new Order(){ Id = "1", Name = "Order #1"},
            new Order(){ Id = "2", Name = "Order #1"},
            new Order(){ Id = "3", Name = "Order #1"},
            new Order(){ Id = "4", Name = "Order #1"},
        };

        public OrderController(ILogger<OrderController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<List<Order>> GetAllAsync()
        {
            return await Task.Run(() =>
            {
                return Orders;
            });
        }


        [HttpGet]
        [Route("{id}")]
        public async Task<Order> GetAsync(string id)
        {
            return await Task.Run(() =>
            {
                var entity = Orders.FirstOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    throw new Exception($"未找到订单:{id}");
                }
                return entity;
            });
        }

        [HttpPost]
        public async Task<Order> CreateAsync(Order order)
        {
            return await Task.Run(() =>
            {
                Orders.Add(order);
                return order;
            });
        }

        [HttpPut]
        [Route("{id}")]
        public async Task<Order> UpdateAsync(string id, Order Order)
        {
            return await Task.Run(() =>
            {
                var entity = Orders.FirstOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    throw new Exception($"未找到订单:{id}");
                }
                entity.Name = Order.Name;
                return entity;
            });
        }

        [HttpDelete]
        [Route("{id}")]
        public async Task<Order> DeleteAsync(string id)
        {
            return await Task.Run(() =>
            {
                var entity = Orders.FirstOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    throw new Exception($"未找到订单:{id}");
                }
                Orders.Remove(entity);

                return entity;
            });
        }
    }
}